/* eslint-disable no-unused-vars */
import Feature from 'ol/Feature';
import { Circle as CircleStyle, Stroke, Style, Fill, Text, RegularShape } from 'ol/style';
import Polygon from 'ol/geom/Polygon';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import GeoJSON from 'ol/format/GeoJSON';

import { pointLonToXy, CalculateContour, CalculateSelect, transformLonlatToNow } from "./util"
import { shipStyleList, shipPointStyleList, LayerZIndex } from "../options"

// 三角形基础信息
const setShipFeature = (row, type = 1) => {
  let shipFeature = new Feature({
    geometry: pointLonToXy(row.longitude, row.latitude),
    name: row.shipName || "",
    mmsi: row.mmsi,
    heading: row.course,
    shipType: type,
    sty: 'sp',
    detail: row
  });
  shipFeature.setId(row.mmsi);
  shipFeature.setStyle(setShipStyle(row, type))
  return shipFeature
}
// 三角形样式
const setShipStyle = (row, type = 1) => {
  var stroke = new Stroke({
    color: row.isSelect ? "#f00" : "#000",
    width: 0.8,
    miterLimit: 1
  });
  let text = row.name
  if (row.isNormal === 1 && type === 1) text += "(E)"
  return new Style({
    image: new RegularShape({
      fill: new Fill({ color: shipStyleList[type].color }),
      stroke: stroke,
      radius: 7,
      points: 3,
      rotation: row.heading === (0 || undefined) ? 0 : Math.PI / (180 / row.heading),
      scale: [1, 2.2]
    }),
    text: new Text({
      textAlign: 'center',
      text: text,
      offsetX: 15,
      offsetY: -10
    })
  })
}
// 圆点基础样式
const setPointShipFeature = (row, type = 1) => {
  let shipFeature = new Feature({
    geometry: pointLonToXy(row.longitude, row.latitude),
    name: row.shipName,
    mmsi: row.mmsi,
    heading: row.course,
    shipType: type,
    sty: 'sp',
    detail: row
  });
  shipFeature.setId(row.mmsi);
  shipFeature.setStyle(setPointShipStyle(row, type))
  return shipFeature
}
// 圆点样式
const setPointShipStyle = (row, type = 1) => {
  // if (row.isNormal === 1 && type === 1) text += "(E)"
  return new Style({
    image: new CircleStyle({
      fill: new Fill({ color: shipPointStyleList[type].color }),
      radius: 3,
    }),
  })
}
// 真轮廓基础信息
const setShipRealOutline = (row, type = 1) => {
  let list = CalculateContour(row).map(m => transformLonlatToNow(m))
  var polygon = new Polygon([list]);
  let shipFeature = new Feature(polygon);
  shipFeature.setStyle(setRealShipStyle(row, type))
  shipFeature.setId(row.mmsi);
  shipFeature.values_.detail = row
  shipFeature.values_.sty = 'sp'
  shipFeature.values_.shipType = type
  return shipFeature
}
// 真轮廓样式
const setRealShipStyle = (row, type) => {
  return new Style({
    fill: new Fill({
      color: shipStyleList[type].color
    }),
    stroke: new Stroke({
      color: row.isSelect ? "#f00" : "#000",
    }),
    text: new Text({
      textAlign: 'center',
      text: row.name,
      offsetX: 15,
      offsetY: -10
    }),
  })
}
// 艏向线样式
const setHeadingStyle = (row) => {
  return new Style({
    image: new RegularShape({
      fill: new Fill({ color: "#000" }),
      stroke: new Stroke({
        color: 'rgba(0,0,0,0)',
        width: 1.25,
      }),
      radius: 2,
      points: 6,
      rotation: Math.PI / (180 / row.heading),
      scale: [0.4, 4],
      displacement: [0, 5]
    }),
    stroke: new Stroke({
      color: '#f00',
      width: 2
    }),
  })
}
// 艏向线
const setShipHeadingLine = (row) => {
  let headingFeature = new Feature({
    mmsi: `head-${row.mmsi}`,
    geometry: pointLonToXy(row.longitude, row.latitude),
  });
  headingFeature.setId(`head-${row.mmsi}`);
  headingFeature.setStyle(setHeadingStyle(row))
  return headingFeature
}
/**
 * 绘制选中框
 * @param {*} list [经度, 纬度]
 * @param {*} type 选中框类型，base:三角和圆点，real:真轮廓
 */
const shipCheckBoxId = "ship_check_box"
const drawCheckBox = (row, type = "base", map) => {
  const list = [row.longitude, row.latitude]
  if (type === "base") {
    drawCheckBoxByRadius(list, map)
  } else {
    drawCheckBoxByReal(row, map)
  }
}
// 点、圆下的选中框
const drawCheckBoxByRadius = (list, map) => {
  // 边长
  var radius = 15
  var layerTmp = map.getLayers().getArray().find(m => m.get("name") === "RADIUS")
  if (!layerTmp) {
    // 添加图层
    layerTmp = new VectorLayer({
      source: new VectorSource({
        features: [],
      }),
      zIndex: LayerZIndex.radius,
      name: "RADIUS",
      type: "base"
    });
    map.addLayer(layerTmp)
  }
  let shipCheckBoxSource = null
  if (layerTmp.get("type") !== "base") {
    shipCheckBoxSource = new VectorSource({
      features: [],
    })
    layerTmp.values_.type = "base"
  } else {
    shipCheckBoxSource = layerTmp.getSource()
  }
  var CheckBoxFeature = shipCheckBoxSource.getFeatureById(shipCheckBoxId);
  if (CheckBoxFeature === null) {
    var longRadius = radius * Math.SQRT2;
    let styless = new Style({
      image: new RegularShape({
        stroke: new Stroke({
          color: "#f00",
          width: 0.8,
          lineDash: [longRadius * 3 / 10, longRadius * 4 / 10, longRadius * 3 / 10, 0]
        }),
        radius: radius,
        points: 4,
        rotation: Math.PI / (180 / 45),
      }),
    })
    let shipFeature = new Feature({
      geometry: pointLonToXy(list[0], list[1]),
    });
    shipFeature.setId(shipCheckBoxId);
    shipFeature.setStyle(styless)
    shipCheckBoxSource.addFeature(shipFeature);
  } else {
    CheckBoxFeature.setGeometry(pointLonToXy(list[0], list[1]));
  }
  layerTmp.setSource(shipCheckBoxSource)
}
// 真轮廓下的选中框
const drawCheckBoxByReal = (row, map) => {
  var layerTmp = map.getLayers().getArray().find(m => m.get("name") === "RADIUS")
  if (layerTmp && layerTmp.get("type") !== "real") {
    layerTmp.values_.type = "real"
  }
  if (!layerTmp) {
    // 添加图层
    layerTmp = new VectorLayer({
      source: new VectorSource({
        features: [],
      }),
      zIndex: LayerZIndex.radius,
      name: "RADIUS",
      type: "real"
    });
    map.addLayer(layerTmp)
  }
  // 绘制开始
  const list = CalculateSelect(row)
  var geojsonObject = {
    type: 'FeatureCollection',
    crs: {
      type: 'name',
      properties: {
        name: 'EPSG: 3857'
      }
    },
    features: []
  };
  for (const item of list) {
    geojsonObject.features.push(
      {
        type: 'Feature',
        geometry: {
          type: "LineString",
          coordinates: item
        }
      }
    )
  }
  var source = new VectorSource({
    features: (new GeoJSON()).readFeatures(geojsonObject)
  });
  layerTmp.setSource(source)
  layerTmp.setStyle(new Style({
    stroke: new Stroke({
      color: "#f00",
      width: 1
    }),
  }))
}
export default {
  // 三角形 - 基本船型
  drawBaseShip: (row, type, shipSource, map) => {
    if (!row) return
    var newshipFeature = shipSource.getFeatureById(row.mmsi);
    console.log("newshipFeature: ", newshipFeature)
    if (newshipFeature === null) {
      shipSource.addFeature(setShipFeature(row, type));
      // 添加艏向线
      // shipSource.addFeature(setShipHeadingLine(row));
    } else {
      row = Object.assign({}, newshipFeature.values_.detail, row)
      newshipFeature.setGeometry(pointLonToXy(row.longitude, row.latitude));
      // 首先判断艏向线是否存在
      // var headingFeature = shipSource.getFeatureById(`head-${row.mmsi}`);
      // if (headingFeature) {
      //   headingFeature.setGeometry(pointLonToXy(row.longitude, row.latitude));
      //   headingFeature.setStyle(setHeadingStyle(row))
      // } else {
      //   shipSource.addFeature(setShipHeadingLine(row));
      // }
      newshipFeature.setStyle(setShipStyle(row, type))
      newshipFeature.values_.detail = row
    }
    // 判断当前船只是否选中，移动选中框
    if (row.isSelect) {
      drawCheckBox(row, "base", map)
    }
  },
  // 圆点
  drawPointShip: (row, type = 1, shipSource, map) => {
    if (!row) return
    if (shipSource.getFeatureById(row.mmsi) === null) {
      shipSource.addFeature(setPointShipFeature(row, type));
    } else {
      var newshipFeature = shipSource.getFeatureById(row.mmsi);
      row = Object.assign({}, newshipFeature.values_.detail, row)
      newshipFeature.setGeometry(pointLonToXy(row.longitude, row.latitude));
      newshipFeature.setStyle(setPointShipStyle(row, type))
      newshipFeature.values_.detail = row
    }
    // 判断是否有艏向线存在，有则删除
    var headingFeature = shipSource.getFeatureById(`head-${row.mmsi}`);
    if (headingFeature) {
      shipSource.removeFeature(headingFeature)
    }
    // 判断当前船只是否选中，移动选中框
    if (row.isSelect) {
      drawCheckBox(row, "base", map)
    }
  },
  // 真轮廓
  drawRealShip: (row, type = 1, shipSource, map) => {
    if (!row) return
    var newshipFeature = shipSource.getFeatureById(row.mmsi);
    if (newshipFeature === null) {
      shipSource.addFeature(setShipRealOutline(row, type));
    } else {
      shipSource.removeFeature(newshipFeature)
      row = Object.assign({}, newshipFeature.values_.detail, row)
      shipSource.addFeature(setShipRealOutline(row, type));
    }
    // 判断是否有艏向线存在，有则删除，真轮廓的艏向线在geojson里面生成
    var headingFeature = shipSource.getFeatureById(`head-${row.mmsi}`);
    if (headingFeature) {
      shipSource.removeFeature(headingFeature)
    }
    // 判断当前船只是否选中，移动选中框
    if (row.isSelect) {
      drawCheckBox(row, "real", map)
    }
  },
}
